#pragma once
#include <iostream>
#include "nocopy.hpp"
#include <string>
#include <cstdint> //uint16_t

#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <strings.h> //bzero

#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>

#include "Log.hpp"
#include "Comm.hpp"
#include "InetAddr.hpp"

static const std::string default_ip = "0.0.0.0"; //static 各个cpp文件中独立一份
static const uint16_t default_port = 8888;

static const int default_sockfd = -1;

using func_t = std::function<std::string(std::string)>;

class UdpServer : public nocopy 
{
public:
    UdpServer(func_t OnMessage, uint16_t port = default_port)
        :_port(port), _sockfd(default_sockfd), _OnMessage(OnMessage)
    {}
    void Init()
    {
        //1. 创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)  //致命错误
        {
            lg.LogMessage(Fatal, "socket error, %d : %s\n", errno, strerror(errno));
            exit(sockfd_err);
        }
        // std::cout << "211";

        lg.LogMessage(Info, "socket created, sockfd: %d\n", _sockfd);

        //2. 绑定
        // std::cout << "211" << std::endl; //注意：不打印\n，这个测试语句其实没有作用

        struct sockaddr_in local;
        bzero(&local, sizeof local);
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_port = htons(_port);

        int ok = ::bind(_sockfd, (const struct sockaddr*)&local, sizeof local);
        if(ok == -1)
        {
            lg.LogMessage(Fatal, "bind error, %d : %s\n", errno, strerror(errno));
            exit(bind_err);
        }
    }
    void Start()
    {
        char buffer[1024];
        while(1)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof peer;
            int n = recvfrom(_sockfd, buffer, 1023, 0, (struct sockaddr*)&peer, &len);

            if(n > 0)
            {
                buffer[n] = 0;
                
                std::cout << InetAddr(peer).PrintDebug() << buffer << std::endl; //回显
                // sendto(_sockfd, buffer, 1024, 0, (const struct sockaddr*)&peer, len);

                std::string response = _OnMessage(buffer);                       //处理后的结果
                sendto(_sockfd, response.c_str(), response.size(), 0, (const struct sockaddr*)&peer, len);
            }
        }
    }
    ~UdpServer()
    {}
private:
    uint16_t _port;
    int _sockfd;
    func_t _OnMessage;
};
